﻿using System;
using System.Text;
using System.IO;

namespace 温湿度和颗粒度监控测试.Common
{
    public class LogHelper
    {
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message">日志信息</param>
        public static void Log(string message)
        {
            string path = $"{Environment.CurrentDirectory}\\Log";
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            path += $"\\{DateTime.Now:yyyy-MM-dd}.log";

            message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {message}\r\n";
            using (FileStream fs = new FileInfo(path).Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                fs.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="ex"></param>
        public static void Error(Exception ex)
        {
            string path = $"{Environment.CurrentDirectory}\\Log";
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            path += $"\\{DateTime.Now.ToString("yyyy-MM-dd")}.log";

            string message = $"\r\nLog Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\r\n" +
                $"Exception Message: {ex.Message}\r\n" +
                $"Exception StackTrace: {ex.StackTrace}\r\n\r\n";
            using (FileStream fs = new FileInfo(path).Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                fs.Write(buffer, 0, buffer.Length);
            }
        }
    }
}
